#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import os
import sys


def main():

    sourcefile=sys.argv[1]
    targetfile=sys.argv[2]

    
    if not os.path.exists(sourcefile):
        print('source is invalid')
        exit(1)
    if not os.path.exists(targetfile):
        print('target is invalid')
        exit(1)

    nodeset = set()
    edgemap = {}

    # print('ok')
    with open(sourcefile,mode='r') as source:
        for line in source:
            #print(line)
            line=line.strip()
            triple = line.split(' ')
            #print(triple)
            nodeset.add(triple[0])
            nodeset.add(triple[1])
            if triple[0] in edgemap.keys():
                edgemap[triple[0]].add(triple[1])
            else:
                edgemap[triple[0]]={triple[1]}
        source.close()
    
    # for file in source_source_set:
    #     print(file+' '+source_line_map[file])


    for k in nodeset:
        for i in nodeset:
            for j in nodeset:
                if i in edgemap.keys() and k in edgemap.keys():
                    if k in edgemap[i] and j in edgemap[k]:
                        #print("add trans edge:"+i+" to "+j+"\n")
                        edgemap[i].add(j)

    
    # for file in source_source_set:
    #     if file in target_source_set:
    #         new_rsf_files.append(file)
    #         new_rsf_target_triple[file]=source_line_map[file]

    # for file in source_source_set:
    #     print(source_line_map[file])
    with open(targetfile,mode='w') as target:
        target.truncate()
        for file in nodeset:
            if file in edgemap.keys():
                for t in edgemap[file]:
                    target.write(file+" "+t+"\n")
        target.close()

    
if __name__=='__main__':
    main()
    
